/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android framework
 * Create Time: 16-2-16 下午6:51
 */

package com.lenovo.framework.rest;

import com.lenovo.framework.util.DLog;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;


/**
 * logging utils when for network debugging
 * @author JeffreyHe
 * @version 1.0
 * @updated 26-一月-2016 15:53:52
 */
public class TimberLoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) {
        Request request = chain.request();

        long t1 = System.nanoTime();
        DLog.i("send:", "Sending %s request on %s%n%s", request.method(), request.url(), request.headers());
        DLog.v("request:", "REQUEST BODY BEGIN\n%s\nREQUEST BODY END", requestBodyToString(request));


        Response response = null;
        try {
            response = chain.proceed(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*if(!"multipart".equals(request.body().contentType().type())){
            DLog.justWrite("request url : " + request.url().toString());
            DLog.justWrite("request body : " + requestBodyToString(request));
            DLog.justWrite("response url : " + response.request().url());
            DLog.justWrite("response body : " + responseBodyToString(response));
        }*/
        long t2 = System.nanoTime();

        DLog.i("receive:", "Received %s response for %s in %.1fms%n%s", request.method(), response.request().url(), (t2 - t1) / 1e6d, response.headers());
        DLog.v("response:", "RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyToString(response));
        return response;
    }

    private static String requestBodyToString(final Request request){
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            if(copy.body() != null) {
                copy.body().writeTo(buffer);
            }
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    private static String responseBodyToString(final Response response){
        try{
            final Response copy = response.newBuilder().build();
            Buffer buffer = new Buffer();
            if(copy.body() != null) {
                BufferedSource source = response.body().source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                buffer = source.buffer().clone();
            }
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}